package com.ledim.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.igexin.sdk.PushManager;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.base.BaseResultInfo;
import com.ledim.db.LedimDBUtils;
import com.ledim.environment.CommonDefind;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.ledim.widget.view.UISwitchButton;
import com.letv.android.young.client.R;
import com.letv.core.db.PreferencesManager;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 设置页
 */
public class SettingActivity extends LeDimBaseActivity
        implements CompoundButton.OnCheckedChangeListener {

    private String mCachePath;
    private ImageView mBack;
    private TextView mLogout;
    private TextView mCacheSize;
    private TextView mVersion;
    private View mCacheLayout;
    private UISwitchButton mSwitchButton;
    private UISwitchButton mSwitchWifi;
    private UISwitchButton mPushMsg;
    private int mUseEnvClickCount = 0; // 进入环境的计数
    private long mUseEnvLastTime = 0;
    private TextView switch_env_tv;
    private LoadingBar mLoading;
    private CommonDialogFragment mLogOutDialog;
    private CommonDialogFragment mSettingClearDialog;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        //---/storage/emulated/0/Android/data/com.letv.android.young.client/cache
        mCachePath = getExternalCacheDir() + "";
        mBack = (ImageView) findViewById(R.id.setting_back_image);
        mLogout = (TextView) findViewById(R.id.user_logout);
        mCacheSize = (TextView) findViewById(R.id.setting_cache);
        mVersion = (TextView) findViewById(R.id.setting_version);
        mCacheLayout = findViewById(R.id.setting_cache_layout);
        mSwitchButton = (UISwitchButton) findViewById(R.id.setting_switch_button);
        mSwitchWifi = (UISwitchButton) findViewById(R.id.setting_switch_wifi);
        mPushMsg = (UISwitchButton) findViewById(R.id.setting_push_msg);
        mBack.setOnClickListener(this);
        mLogout.setOnClickListener(this);
        mCacheLayout.setOnClickListener(this);

        mCacheSize.setText(getCacheSize());
        mSwitchButton.setChecked(PreferencesManager.getInstance(this).isSkip());
        mSwitchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PreferencesManager.getInstance(SettingActivity.this).setSkip(isChecked);
            }
        });

        mSwitchWifi.setChecked(!PreferencesManager.getInstance().isShow3gDialog());
        mSwitchWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PreferencesManager.getInstance().setShow3gDialog(!isChecked);
            }
        });
        //设置push开关
        mPushMsg.setChecked(PushManager.getInstance().isPushTurnedOn(this));
        mPushMsg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                LedimSpUtils.setPushMsg(isChecked);
                if (isChecked) {
                    PushManager.getInstance().turnOnPush(SettingActivity.this);
                } else {
                    PushManager.getInstance().turnOffPush(SettingActivity.this);
                }
            }
        });

        if (!LedimSpUtils.isLogin()) {
            mLogout.setVisibility(View.GONE);
        } else {
            mLogout.setVisibility(View.VISIBLE);
        }
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            mVersion.setText("v" + packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        findViewById(R.id.iv_logo).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_back_image:
                finish();
                break;
            case R.id.setting_cache_layout:
                showClearDialog();
                break;
            case R.id.user_logout:
                showLogOutDialog();
                break;
            case R.id.iv_logo:
                if (LogUtil.isDebug) {
                    clickAppIcon(v);
                }
                break;
            case R.id.switch_env_tv:
                LedimSpUtils.setLogin(false);
                LedimSpUtils.setUid("");
                LedimSpUtils.setToken("");
                CommonDefind.DEBUG_MARK = !CommonDefind.DEBUG_MARK;
                LedimSpUtils.setDebugMark(CommonDefind.DEBUG_MARK);
                LedimApiServiceFactory.resetEnvironment();
                resetEventTextView();
                LedimDBUtils.clearAllData();
                break;
        }
    }

    /**
     * 二次确认清除缓存弹窗
     */
    private void showClearDialog() {
        if (mSettingClearDialog == null) {
            mSettingClearDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, "清除缓存：除秽之刃，斩！", "确定", "取消", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            File file = new File(mCachePath);
                            ToastUtil.toast("清除缓存" + getCacheSize());
                            deleteFile(file);
                            mCacheSize.setText("0.00M");
                        }

                        @Override
                        public void onClickNegative(View view) {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
        }
        mSettingClearDialog.showDialog(getSupportFragmentManager());
    }

    private String getCacheSize() {
        String cache = "";
        try {
            long fileSize = 0;
            File file = new File(mCachePath);
            fileSize = getFileSize(file);
            cache = formatFileSize(fileSize);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return cache;
    }

    public long getFileSize(File f) throws Exception {
        long size = 0;
        if (f.isFile()) {
            return f.length();
        }
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public String formatFileSize(long fileS) {// 转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS > 0) {
            if (fileS < 1024) {
                fileSizeString = df.format((double) fileS) + "B";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "K";
            } else if (fileS < 1073741824) {
                fileSizeString = df.format((double) fileS / 1048576) + "M";
            } else {
                fileSizeString = df.format((double) fileS / 1073741824) + "G";
            }
        }
        return fileSizeString;
    }

    public void deleteFile(File file) {
        File flist[] = file.listFiles();
        if (flist != null) {
            for (int i = 0; i < flist.length; i++) {
                if (flist[i].isDirectory()) {
                    deleteFile(flist[i]);
                } else {
                    flist[i].delete();
                }
            }
        } else {

        }

    }

    /**
     * 确认退出弹窗
     */
    private void showLogOutDialog() {
        if (mLogOutDialog == null) {
            mLogOutDialog =
                    CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_VERCTIAL_TYPE, "确认要退出登录吗？", "即使不舍还是要退出", "我就是随便点点", new LedimDialogClickListner() {
                        @Override
                        public void onClickPositive(View view) {
                            logout();
                        }

                        @Override
                        public void onClickNegative(View view) {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
        }
        mLogOutDialog.showDialog(getSupportFragmentManager());
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    private void resetEventTextView() {
        if (switch_env_tv != null) {
            if (LedimSpUtils.getDebugMark()) {
                switch_env_tv.setText("目前测试环境");
            } else {
                switch_env_tv.setText("目前正式环境");
            }
        }
    }

    private void clickAppIcon(final View v) {
        long current_time = System.currentTimeMillis();
        long difference = current_time - mUseEnvLastTime;
        if (difference - 300 <= 0 || (mUseEnvLastTime == 0 && mUseEnvClickCount == 0)) {
            mUseEnvClickCount++;
            if (mUseEnvClickCount >= 3) {
                // enter
                if (switch_env_tv == null) {
                    switch_env_tv = (TextView) findViewById(R.id.switch_env_tv);
                    switch_env_tv.setVisibility(View.VISIBLE);
                    switch_env_tv.setOnClickListener(this);
                    resetEventTextView();
                }
                v.setClickable(false);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        v.setClickable(true);
                    }
                }, 1000l); // 延长一秒钟可以点击
                mUseEnvClickCount = 0;
                mUseEnvLastTime = 0;
            }
            mUseEnvLastTime = current_time;
        } else {
            mUseEnvClickCount = 1;
            mUseEnvLastTime = current_time;
        }
    }

    /**
     * 用户注销
     */
    private void logout() {
        if (mLoading == null) {
            mLoading = new LoadingBar(this);
        }
        mLoading.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .logout()
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultInfo>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      mLoading.dismiss();
                                      ToastUtil.toast("退出失败");
                                  }

                                  @Override
                                  public void onNext(BaseResultInfo data) {
                                      super.onNext(data);
                                      mLoading.dismiss();
                                      if (data != null) {
                                          if (data.success) {
                                              LedimSpUtils.setUid("");
                                              LedimSpUtils.setToken("");
                                              LedimSpUtils.setLogin(false);

                                              ToastUtil.toast("退出成功");
                                              Intent intent =
                                                      new Intent(SettingActivity.this, MainActivity.class);
                                              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                              startActivity(intent);
                                              overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                                          } else {
                                              //登录失败
                                              ToastUtil.toast(data.message);
                                          }
                                      }
                                  }
                              });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoading != null) {
            mLoading.dismiss();
        }
    }
}
